/** @jsxImportSource @emotion/react */
import * as React from "react";
import {css} from "@emotion/react";
import {
  CCell, Cell, Table, TableBody, TableRow, Text, TableHead, TextArea, BlobInputList,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink, useItemInputControl} from "../../common/base";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";
import {useMeasureInpFilter} from "../../common/hooks";
import {objNestSet} from "../../../common/tool";
import {useOmnipotentPrefCs, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";
import {tail附页} from "./orcBase";

const items检验项 = [
    ['使登证', [{t:'1资料审查',s:9},{t:'（1）安全管理资料',s:3}], '使用登记证', ],
    ['规章制', [{},], '安全管理规章制度与安全操作规则', ],
    ['上岗证', [{},], '作业人员上岗持证情况', ],
    ['定检报', [{},{t:'（2）技术档案资料',s:2}], '定期检验报告', ],
    ['竣验收资', [{},], '设计和安装、改造、维修等施工、竣工验收资料', ],
    ['日常运行', [{},{t:'（3）运行状况资料',s:4}], '日常运行维护记录', ],
    ['隐患治', [{},], '隐患排查治理记录', ],
    ['维修资', [{},], '改造、维修资料', ],
    ['故障记', [{},], '故障与事故记录', ],
    ['地面泄漏', [{t:'2宏观检查',s:6,cs:1},{cs:-1}], '（1）地面泄漏情况', ],
    ['管位置', [{}, {t:'（2）位置与走向',s:3}], '管道位置', ],
    ['管埋深', [{},], '管道埋深', ],
    ['管走向', [{},], '管道走向', ],
    ['地面标', [{},{cs:-1}], '（3）地面标志', ],
    ['地环境', [{},{cs:-1}], '（4）管道沿线地表环境', ],
    ['跨越段', [{t:'2宏观检查',s:5,cs:1},{cs:-1}], '（5）跨越管段', ],
    ['穿越段', [{},{cs:-1}], '（6）穿越管段', ],
    ['凝水', [{},{cs:-1}], '（7）凝水缸', ],
    ['阀补偿节', [{},{cs:-1}], '（8）阀门、法兰、补偿节等管道元件', ],
    ['宏观检他', [{},{cs:-1}], '（9）其他', ],
    ['防腐保层', [], '3防腐（保温）层', ],
    ['电绝装', [{t:'4电性能测试',s:2}], '（1）电绝缘装置' ],
    ['电连续', [{} ], '（2）电连续性能' ],
    ['护电位', [{t:'5阴极保护系统测试',s:8,cs:1},{cs:-1}], '（1）保护电位', ],
    ['牺牲阳电', [{},{cs:-1}], '（2）牺牲阳极输出电流、开路电位', ],
    ['焊材质量', [{},{cs:-1}], '（3）管内电流', ],
    ['阳床接地', [{},{cs:-1}], '（4）辅助阳极床和牺牲阳极接地电阻', ],
    ['保护率', [{},{t:'（5）阴极保护运行状况',s:4}], '保护率', ],
    ['运行率', [{},], '运行率', ],
    ['排流效', [{},], '排流效果', ],
    ['阴极保护', [{},], '阴极保护系统设备和排流设施', ],
    ['壁厚测', [], '6壁厚测定', ],
    ['腐蚀性', [], '7介质腐蚀性调查', ],
    ['安保装', [], '8安全保护装置检验', ],
    //【特别注意】可定做项目序号=@代码耦合@！ : 固定数目【给用户增加项目】其它1 其他1: {"t":''}
    ['其它1', [], ' ', ],
    ['其它2', [], ' ', ],
    ['其它3', [], ' ', ],
    ['其它4', [], ' ', ],
];

export const itemA检验项: string[] = ['附页说明',  ];
items检验项.forEach(([name, title, initIsp], i: number) => {
  itemA检验项.push(name as string);
});
const 检查结果选=['√', '×', '—'];

const config项目上=items检验项.slice(0,20);
//似乎原本？？应该和 “目录” 项目列表合并集成一起的编辑器， #单独分出？ #这丫也好，更清晰点的编辑操作。
export const AppendixPage =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, }: InternalItemProps, ref
    ) => {
      const {inp, setInp} = useItemInputControl({ref});
      const [getInpFilter] = useMeasureInpFilter(null, itemA检验项,);
      const titNode=useOmnipotentPrefTitle({config: config项目上});
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {config项目上.map(([name, _1, _2, unit]: any, i: number) => {
              return (<React.Fragment key={i}>
                <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                  {titNode[i]}
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    检查结果：
                    <BlobInputList value={inp?.[name]?.r || ''} datalist={检查结果选} rows={1}
                                   style={{display: 'inline-flex', width: '9rem', maxWidth: '100%', fontSize: '1rem',}}
                                   listStyle={css({fontSize: '1rem',})}
                                   onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>
                  </div>
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    备注：
                    <BlobInputList value={inp?.[name]?.m || ''}  rows={2}
                                   style={{display: 'inline-flex', width: '16rem', maxWidth: '100%',}}
                                   onListChange={v => objNestSet(name, 'm', v || undefined, inp, setInp)}/>
                  </div>
                </div>
              </React.Fragment>);
            })}
            <hr/>
            说明：
            <TextArea  value={inp?.附页说明 ||''} rows={6}
                       onChange={e => setInp({ ...inp, 附页说明: e.currentTarget.value||undefined}) } />
            {children}
          </InspectRecordLayout>
      );
  });

const config项目下=items检验项.slice(20);
export const AppendixPage2 =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, }: InternalItemProps, ref
    ) => {
      const {inp, setInp} = useItemInputControl({ref});
      const [getInpFilter] = useMeasureInpFilter(null, itemA检验项,);
      const titNode=useOmnipotentPrefTitle({config: config项目下, baseSeq:20 });
      let iaddc=0;
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {config项目下.map(([name, _1, item, unit]: any, i: number) => {
              let adName='';
              if(' '===item){
                  iaddc++;
                  adName='其它'+iaddc;
              }
              return (<React.Fragment key={i}>
                <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                  {titNode[i]}{' '===item && inp?.[adName]?.t}&nbsp;
                  { ' '===item && <> 项目：
                           <BlobInputList value={inp?.[adName]?.t ||''} style={{display: 'inline-flex', width: '15rem'}}  rows={2}
                                       onListChange={v => objNestSet(adName,'t',v||undefined, inp, setInp) }/>
                    </>
                  }
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    检查结果：
                    <BlobInputList value={inp?.[name]?.r || ''} datalist={检查结果选} rows={1}
                                   style={{display: 'inline-flex', width: '9rem', maxWidth: '100%', fontSize: '1rem',}}
                                   listStyle={css({fontSize: '1rem',})}
                                   onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>
                  </div>
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    备注：
                    <BlobInputList value={inp?.[name]?.m || ''}  rows={2}
                                   style={{display: 'inline-flex', width: '16rem', maxWidth: '100%',}}
                                   onListChange={v => objNestSet(name, 'm', v || undefined, inp, setInp)}/>
                  </div>
                </div>
              </React.Fragment>);
            })}
            <hr/>
            说明：
            <TextArea  value={inp?.附页说明 ||''} rows={6}
                       onChange={e => setInp({ ...inp, 附页说明: e.currentTarget.value||undefined}) } />
            {children}
          </InspectRecordLayout>
      );
  });

const tailRender = (orc: any, name: string, lix: number, unit: any) => {
  const nneedbig = orc?.[name]?.r?.length >= 3 || (!orc?.[name]?.r);
  return <>
    <CCell><Text css={{fontSize: nneedbig ? '0.875rem' : '1.15rem'}}>{orc?.[name]?.r ?? '／'}</Text></CCell>
    <CCell>{orc?.[name]?.m ?? '／'}</CCell>
  </>;
}

//检验报告附页；     【特别注意】 其它1 可定做项目序号=@代码耦合@！
export const AppendixPageVw = ({orc, rep,op}: { orc: any, rep: any,op?:boolean }
) => {
  const configNew =React.useMemo(()=>{
        const mainp=items检验项.slice(0,34);
        let arr= [] as string[];
        for(let i = 0; i < 4; i++) {
          const name='其它'+(i+1);
          if(orc?.[name]?.t)   arr.push(name);
        }
        const rspanA=arr.length;
        let add=[];
        for(let k = 0; k < rspanA; k++) {
          const name=arr[k];
          add.push( [name, [ ], orc?.[name]?.t ] );
        }
        return [...mainp, ...add ];
  },[orc?.其它1, orc?.其它2, orc?.其它3, orc?.其它4]);

  const [renderP1,renderP2] = useOmnipotentPrefCs({orc, config: configNew,
                      split:[19],tag:'ApxIspItms', tailRender, pcols: 2, noNo: false, unitCel: false});
  return <>
    <div css={{"@media print": {paddingBottom: '5.5rem', pageBreakInside: 'avoid'}}}>
      <Text id='AppendixPage' variant="h2" css={{textAlign: 'center', marginTop: '1rem',
      }}>公用管道年度检查{op?'记录':'报告'}附页</Text>
      <div css={{display: 'flex', justifyContent: 'space-between'}}>
        <Text></Text>
        <Text>{op?'记录':'报告'}编号：{rep.isp.no}</Text>
      </div>
    </div>
    <Table fixed={ ["3.6%", "9%", "13%", "%", "15%","24%"] }
              css={{borderCollapse: 'collapse', "@media print": {marginTop: '-5.5rem'}}} tight miniw={800}>
      <TableHead>
        <TableRow>
          <CCell><Text css={{fontSize: '0.75rem'}}>序号</Text></CCell><CCell colSpan={3}>检查项目及其内容</CCell><CCell>检查结果</CCell><CCell>备注</CCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <RepLink rep={rep} tag={'AppendixPage'}>
          {renderP1}
        </RepLink>
        <RepLink rep={rep} tag={'ApxIspItms_20'}>
          {renderP2}
          <TableRow>
            <Cell split={true} colSpan={6}>
              <div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                说明：<br/>{orc?.附页说明 || '／'}
              </div>
            </Cell>
          </TableRow>
        </RepLink>
      </TableBody>
    </Table>
    <TailMenRowIspCheck  orc={orc} rep={rep} cap='检查' href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ProjectList#ProjectList`}>
    </TailMenRowIspCheck>
    {tail附页}
  </>;
};
